package com.zzuli.fitness.controller;

import com.zzuli.fitness.entity.Coach;
import com.zzuli.fitness.entity.Course;
import com.zzuli.fitness.entity.OrderInfo;
import com.zzuli.fitness.entity.User;
import com.zzuli.fitness.service.CoachService;
import com.zzuli.fitness.service.CourseService;
import com.zzuli.fitness.service.OrderService;
import com.zzuli.fitness.service.UserService;
import com.zzuli.fitness.utils.FitnessUtil;
import com.zzuli.fitness.utils.QRBarCodeUtil;
import com.zzuli.fitness.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

@Api(tags = "预约接口")
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Value("${fitness.path.upload}")
    private String uploadPath;

    @Value("${fitness.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private CoachService coachService;

    /**
     * 生成二维码并保存到指定的目录下
     */
    @GetMapping("/createCode")
    public Result createQrCodeForFile(@RequestParam("name")String name,
                                      @RequestParam("phone")String phone,
                                      @RequestParam("openid")String openid,
                                      @RequestParam("courseId")Integer courseId,
                                      @RequestParam("coachId")Integer coachId){
        User user = userService.selectUserByOpenId(openid);
        //生成订单号
        String orderNum = RandomStringUtils.randomAlphanumeric(10);
        //生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderNum);
        orderInfo.setUserId(user.getId());
        orderInfo.setProgramId(courseId);
        orderInfo.setCoachId(coachId);
        orderInfo.setUserName(name);
        orderInfo.setPhone(phone);
        orderInfo.setCreateTime(new Date());
        //生成二维码,并存储路径进数据库
        File file = new File(uploadPath);
        String fileName = FitnessUtil.generateUUID() + ".png";
        String codePath = domain + contextPath + "/order/getQRCode/" + fileName;
        orderInfo.setQrcode(codePath);
        orderService.insertOrderInfo(orderInfo);
        QRBarCodeUtil.createCodeToFile(orderNum, file, fileName);

        //课程可预约人数减一
        Course course = courseService.getById(courseId);
        Integer amount = course.getAmount();
        if (amount != null){
            amount--;
            course.setAmount(amount);
            courseService.updateById(course);
        }

        Coach coach = coachService.selectCoachById(orderInfo.getCoachId());
        orderInfo.setCoachName(coach.getName());
        orderInfo.setProgramName(course.getName());
        orderInfo.setDay(course.getDay());
        orderInfo.setBeginTime(course.getBeginTime());
        orderInfo.setEndTime(course.getEndTime());
        return Result.ok(orderInfo);
    }

    /**
     * 将二维码输出到页面显示
     * @param response
     */
    @RequestMapping(path = "/getQRCode/{fileName}", method = RequestMethod.GET)
    public void getQRCode(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失败！！");
        }
    }

    @ApiOperation(value = "查看所有预约")
    @GetMapping("/findAllOrder")
    public Result findAllOrder(@RequestParam String openid){
        List<OrderInfo> list = orderService.findAllOrderByOpenId(openid);
        for (int i=0;i<list.size();i++){
            OrderInfo orderInfo = list.get(i);
            Coach coach = coachService.selectCoachById(orderInfo.getCoachId());
            Course course = courseService.selectCourseById(orderInfo.getProgramId());
            orderInfo.setCoachName(coach.getName());
            orderInfo.setProgramName(course.getName());
            list.set(i, orderInfo);
        }
        return Result.ok(list);
    }

    @ApiOperation(value = "查看预约详情信息")
    @GetMapping("/findOrderInfo")
    public Result findOrderInfo(@RequestParam String id) {
        OrderInfo orderInfo = orderService.findOrderInfoById(id);
        Coach coach = coachService.selectCoachById(orderInfo.getCoachId());
        Course course = courseService.selectCourseById(orderInfo.getProgramId());
        orderInfo.setCoachName(coach.getName());
        orderInfo.setProgramName(course.getName());
        orderInfo.setDay(course.getDay());
        orderInfo.setBeginTime(course.getBeginTime());
        orderInfo.setEndTime(course.getEndTime());
        return Result.ok(orderInfo);
    }
}
